<template>
  <div>
    <el-form :ref="ruleFormRef" :rules="rules" :model="formInline">
      <el-row>
        <el-form-item label="订单时间">
          <el-date-picker
            v-model="formInline.createTime"
            type="daterange"
            :style="{ ...styleConfig.inputStyle, width: '220px' }"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-popover
              ref="popover1"
              placement="top-start"
              width="200"
              trigger="hover"
            >
              <template #reference>
                <el-input
                  placeholder="粘贴图片"
                  @paste="(e) => handlePaste(e, row)"
                ></el-input>
              </template>
              <div>
                <el-input v-model="msgRemark" placeholder="备注"></el-input>
              </div>
            </el-popover>
            <el-button type="primary" icon="Search" @click="onSearch"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="onReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-row>
    </el-form>
    <el-table
      v-loading="loading"
      ref="tableRef"
      height="300"
      :data="orderData"
      row-key="orderNo"
      :current-row-key="currentRowKey"
      highlight-current-row
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column
        align="center"
        type="selection"
        width="50"
        fixed="left"
      />
      <el-table-column align="center" type="index" width="70" label="序号" />
      <el-table-column
        align="center"
        prop="OrderCode"
        :width="flexColumnWidth('订单编号', 'OrderCode', orderData) + 10"
        label="订单编号"
      />
      <el-table-column align="center" prop="ProduceCode" label="工单编号" />
      <el-table-column
        align="center"
        prop="CustomerName"
        label="客户"
        :width="flexColumnWidth('客户', 'CustomerName', orderData) + 20"
      />
      <el-table-column align="center" prop="secCustomer" label="子客户" />
      <el-table-column align="center" prop="OrderClerkName" label="接单员" />
      <el-table-column
        align="center"
        prop="GateType"
        label="门板类型"
        :width="flexColumnWidth('门板类型', 'GateType', orderData) + 10"
      />
      <el-table-column align="center" prop="LeafCount" label="门叶数量" />
      <el-table-column align="center" prop="OrderRemark" label="订单备注" />
      <el-table-column
        align="center"
        prop="CreateTime"
        label="创建时间"
        :formatter="(row) => timeStampFormatter(row.CreateTime, true)"
        :width="flexColumnWidth('日期日期', 'CreateTime', orderData) - 60"
      />
      <el-table-column
        align="center"
        prop="OrderTime"
        label="下单时间"
        :formatter="(row) => timeStampFormatter(row.OrderTime, true)"
        :width="flexColumnWidth('日期日期', 'OrderTime', orderData) - 60"
      />
      <el-table-column
        align="center"
        prop="FinishTime"
        label="入库时间"
        :formatter="(row) => timeStampFormatter(row.FinishTime, true)"
        :width="flexColumnWidth('日期日期', 'FinishTime', orderData) - 60"
      />
      <!-- <el-table-column
        align="center"
        prop="FinishTime"
        label="出库日期"
        :formatter="(row) => timeStampFormatter(row.FinishTime)"
      /> -->
      <el-table-column align="center" prop="IsCancelOver" label="是否取消" />
      <el-table-column align="center" prop="IsFinish" label="是否完成" />
      <el-table-column align="center" prop="IsOrderOverTime" label="是否完结" />
      <el-table-column align="center" prop="Urgent" label="是否加急" />
      <el-table-column
        align="center"
        prop="nField"
        label="订单属性"
        :width="flexColumnWidth('订单属性', 'nField', orderData) + 10"
      >
        <!-- <template v-slot="scope">
          <template v-for="(item, key) in scope.row" :key="key">
            <span v-if="key.includes('Field')" style="margin-right: 4px">
              {{ item }}
            </span>
          </template>
</template> -->
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作">
        <template #default="{ row }">
          <el-input
            placeholder="粘贴图片"
            @paste="(e) => handlePaste(e, row)"
          ></el-input>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.PageIndex"
      v-model:limit="queryParams.PageSize"
      @pagination="getList"
    />
    <div class="attributes-board" v-loading="loadingInfo">
      <el-empty
        v-if="selectRows.length !== 1"
        :description="
          selectRows.length == 0 ? '请选择订单，查看订单属性' : '暂不支持多选'
        "
      />
      <el-descriptions
        v-else-if="!loadingInfo"
        title="订单属性"
        direction="vertical"
        border
      >
        <el-descriptions-item label="基本属性">
          <template #label>
            基本属性
            <el-button
              link
              type="primary"
              @click="router.push(`./detail?id=${orderInfo.OrderInfo.OrderId}`)"
              >更多属性
            </el-button>
          </template>
          <div class="flex flex-wrap">
            <div
              class="mr-4"
              v-for="(item, index) in orderInfo.baseInfo"
              :key="index"
            >
              <b>{{ item.key }}：</b>{{ item.value || "/" }}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item width="400" label="订单工序进度" rowspan="2">
          <el-timeline style="max-width: 600px">
            <el-timeline-item
              v-for="(activity, index) in orderInfo.Produces[0].TrackList"
              :key="index"
              type="primary"
              hollow
              :timestamp="timeStampFormatter(activity.CreateTime)"
            >
              {{ activity.ProcessName }}
            </el-timeline-item>
          </el-timeline></el-descriptions-item
        >
        <el-descriptions-item label="留言附图">
          <div
            v-if="orderInfo.MessageList.length !== 0"
            class="h-[100px] overflow-y-scroll overflow-x-hidden"
          >
            <el-row
              :gutter="10"
              class="relative"
              v-for="(item, index) in orderInfo.MessageList"
              :key="index"
            >
              <el-col :span="16">
                <div class="flex items-center">
                  <div class="flex items-center my-1">
                    <UserFilled size="4" class="mr-1" />
                    <div class="text-gray-500 text-sm">
                      {{ item.SendName }}
                    </div>
                  </div>
                  <div class="text-xs ml-2">
                    {{ timeStampFormatter(item.CreateTime) }}
                  </div>
                </div>
                <div class="text-gray-700 text-[15px]">
                  {{ item.Remark }}
                  <el-button
                    type="danger"
                    link
                    icon="Delete"
                    @click="handleDeleteMsg(item.MsgId)"
                  />
                </div>
              </el-col>
              <el-col :span="8">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="item.AttatchUrl"
                  fit="contain"
                ></el-image>
              </el-col>
            </el-row>
          </div>
          <el-empty
            v-else
            :image-size="60"
            style="width: 100%; height: 100px"
            description="无"
          ></el-empty>
        </el-descriptions-item>
        <el-descriptions-item label="结算属性">
          金额：{{ orderInfo.OrderInfo.OrderMoney }}
        </el-descriptions-item>
        <el-descriptions-item label="图片" width="400" style="display: flex">
          <el-image
            style="width: 100px; height: 100px; margin: 1px"
            v-for="(item, index) in orderInfo.PictureList"
            :key="index"
            :src="item.PictureUrl"
            :preview-src-list="
              orderInfo.PictureList.map((item) => item.PictureUrl)
            "
          ></el-image>
          <el-empty
            :image-size="60"
            style="width: 100%; height: 100px"
            v-if="orderInfo.PictureList.length == 0"
            description="无"
          ></el-empty>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>
<script setup>
import { onMounted } from "vue";
import {
  orderInfoApi,
  orderListApi,
  msgAddApi,
  msgDeleteApi,
} from "../../../../../api/order/list";
import { timeStampFormatter } from "../../../../../utils";
import { flexColumnWidth } from "@/utils/flexCol.js";
import { uploadImg2 } from "@/api/upload.js";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
// 获取当前月份的第一天
const firstDayOfMonth = dayjs().startOf("month").format("YYYY-MM-DD");
// 获取当前月份的最后一天
const lastDayOfMonth = dayjs().endOf("month").format("YYYY-MM-DD");

const formInline = ref({
  shape: "",
  orderId: "",
  id: "",
  orderNo: "",
  ProduceCode: "",
  remark: "",
  editReason: "",
  createTime: [firstDayOfMonth, lastDayOfMonth],
});
const orderData = ref([]);
const orderInfo = ref({});
const selectRows = ref([]);
const loading = ref(false);
const loadingInfo = ref(false);

const styleConfig = {
  inputStyle: {
    width: "100px",
    marginRight: "4px",
  },
};
const ruleFormRef = ref();
const tableRef = ref();
const currentRowKey = ref();

const queryParams = ref({
  PageSize: 10,
  PageIndex: 1,
});
const total = ref(0);

const rules = reactive({
  editReason: [
    {
      required: true,
      message: "请输入修改理由",
      trigger: "blur",
    },
  ],
});
/** 查询定时任务列表 */
function getList() {
  loading.value = true;
  orderListApi({ ...queryParams.value }).then((res) => {
    total.value = res.TotalCount;
    loading.value = false;
    orderData.value = res.Data || [{ orderNo: "123" }];
    orderData.value.forEach((item, index) => {
      item.nField = "";
      let str = "";
      for (let key in item) {
        if (typeof item[key] == "boolean") {
          item[key] = item[key] ? "是" : "否";
        }
        if (key.includes("Field")) {
          str += item[key] + " ";
        }
      }
      item.nField = str;
    });
  });
}

function getData() {
  loading.value = true;
  orderListApi({
    BeginDate: dayjs(formInline.value.createTime[0]).format("YYYY-MM-DD"),
    EndDate: dayjs(formInline.value.createTime[1]).format("YYYY-MM-DD"),
  }).then((res) => {
    loading.value = false;

    total.value = res.TotalCount;
    orderData.value = res.Data;
    orderData.value.forEach((item, index) => {
      item.nField = "";
      let str = "";
      for (let key in item) {
        if (typeof item[key] == "boolean") {
          item[key] = item[key] ? "是" : "否";
        }
        if (key.includes("Field")) {
          str += item[key] + " ";
        }
      }
      item.nField = str;
    });
  });
}
onMounted(() => {
  getData();
});
function handleClick() {}
function onSearch() {
  if (formInline.value.createTime) {
    getData();
  }
}
function onReset() {
  getData();
}
function handleSelectionChange(selection) {
  selectRows.value = selection;
}
async function handleRowClick(row) {
  tableRef.value.clearSelection();
  tableRef.value.toggleRowSelection(row);
  if (selectRows.value.length == 1) {
    loadingInfo.value = true;
    let res = await orderInfoApi(selectRows.value[0].OrderId);
    if (res.IsSuccess) {
      orderInfo.value = res;
      // 处理基本属性
      let baseInfo = [];
      orderInfo.value.SiteAttrs.split(",").forEach((item, index) => {
        baseInfo.push({
          key: item,
          value: orderInfo.value.OrderInfo["Field" + (index + 1)],
        });
      });
      orderInfo.value.baseInfo = baseInfo;
    }
    loadingInfo.value = false;
  }
  // currentRowKey.value = row.orderNo;
}
const msgRemark = ref("");
async function handlePaste(e) {
  if (selectRows.value.length !== 1) {
    ElMessage.error("请先选择一条订单");
    return;
  }
  // 粘贴图片
  //获取clipboardData对象
  let data = e.clipboardData || window.clipboardData;
  //获取图片内容
  let file = data.items[0].getAsFile();
  //判断是不是图片，最好通过文件类型判断
  var isImg = file && file.type.includes("image");
  var reader = new FileReader();
  if (isImg) {
    //将文件读取为 DataURL
    // reader.readAsDataURL(blob);
  } else {
    ElMessage.error("粘贴失败，未找到截图");
  }
  const res = await uploadImg2({
    Name: "lastModified" + file.name.split(".")[0],
    img: file,
  });
  await msgAddApi({
    OrderId: selectRows.value[0].OrderId,
    AttatchUrl: "https://order.taomen365.com/" + res.name,
    Remark: msgRemark.value,
  });
  ElMessage.success("提交成功");
  handleRowClick(selectRows.value[0]);
  msgRemark.value = "";
  // //文件读取完成时触发
  // reader.onload = function (event) {
  //   //获取base64流
  //   var base64_str = event.target.result;
  // };
}
function handleClick1() {
  console.log("aste");
}
const popoverVisible = ref(false);
async function handleDeleteMsg(id) {
  try {
    await ElMessageBox.confirm("确定删除吗", "提示", {
      type: "warning",
    });
    await msgDeleteApi(id);
    ElMessage.success("删除成功");
    handleRowClick(selectRows.value[0]);
  } catch (error) {}
}
</script>
<style>
.attributes-board {
  border: 1px solid #ddd;
  margin-top: 20px;
  padding: 10px;
  padding-top: 0;
  min-height: 300px;
}

.desc-item {
  width: 10px;
  padding: 0;
}

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}
</style>
